import React from "react";
import SearchBar from "../../components/search-bar";
import TableHeader from "../../components/table-header";
import Moment from "moment";
import Pagination from "../../components/pagination";
import {Link} from "react-router";

export default class User extends React.Component {

    constructor(...props) {
        super(...props);
        this.state = {
            list: [],
            count: 0,
            page: 1,
            size: 30
        };
    }

    loadData(page = this.state.page, keyword = '') {
        if (page != this.state.page) {
            this.setState({page});
        }
        let max = this.state.list.length > 0 && page > 1 ? this.state.list[this.state.list.length - 1].createdAt : 0;
        this.ajax && this.ajax.abort();
        this.ajax = $.get('/admin/user/list', {
            max,
            size: this.state.size,
            keyword
        }, (data)=> {
            this.setState({list: data.list, count: Number(data.count)});
        });
    }

    componentDidMount() {
        this.loadData();
    }

    componentWillUnMount() {
        this.ajax && this.ajax.abort();
    }

    onSearch(keyword) {
        this.loadData(1, keyword);
    }

    render() {
        const list = this.state.list.map((item, index)=> {
            return (
                <tr key={item.openid}>
                    <td>{item.openid}</td>
                    <td>{item.nickname}</td>
                    <td><a href={item.avatar} target="_blank"><img width="24" height="24" src={item.avatar}
                                                                   className="img-responsive"/></a></td>
                    <td>{item.realname}</td>
                    <td>{item.phone}</td>
                    <td>{new Moment(item.createdAt * 1000).format('MM-DD HH:mm')}</td>
                    <td><Link to={'/user/'+item.openid+'/edit'}>编辑</Link></td>
                </tr>
            )
        });
        return (
            <div className="site-user user-index">
                <h2>用户列表</h2>
                <p>当前用户数：{this.state.count}</p>
                <SearchBar placeholder="姓名/昵称/手机" onSearch={keyword=>this.onSearch(keyword)}/>
                <div className="table-responsive">
                    <table className="table table-bordered">
                        <TableHeader sections={['openid','昵称','头像','姓名','电话','注册时间','操作']}/>
                        <tbody>{list}</tbody>
                    </table>
                </div>
                <Pagination pageSize={this.state.size} loader={(page)=>this.loadData(page)} totalRows={this.state.count}
                            currentPage={this.state.page}/>
            </div>
        )
    }
}